package org.xukai.common.util;

import com.alibaba.fastjson.JSON;
import org.apache.commons.io.IOUtils;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author lf
 * @desc
 * @date 2019-01-08-9:59
 */
public class DesensitizationUtil {

    /**
     * 匹配json form表单 xml中password
     */
    private static Pattern PASSWORD_PATTERN = Pattern.compile(".{0,12}?[pP][aA][sS][sS][wW][oO]?[rR]?[dD]\\\\?\":\\\\?\"(.+?)\\\\?\"" +
            "|.{0,12}?[pP][aA][sS][sS][wW][oO]?[rR]?[dD]=(.+?)[&\\s]+" +
            "|.{0,12}?[pP][aA][sS][sS][wW][oO]?[rR]?[dD]</name><value>(.+?)</value>");

    /**
     * 处理日志字符串，返回脱敏后的字符串
     * @param message
     * @return
     */
    public static String desensitizeMsg(final String message){
        String searchString = message;
        Matcher matcher = PASSWORD_PATTERN.matcher(searchString);
        StringBuilder sb = new StringBuilder();
        while (matcher.find()) {
            int startIndex = -1;
            int endIndex = -1;
            for (int i = 0; i < 3; i++) {
                int start = matcher.start(i + 1);
                if (start != -1) {
                    startIndex = start;
                    endIndex = matcher.end(i + 1);
                    break;
                }
            }
            if (startIndex == -1) {
                //匹配不到()中的密码值
                continue;
            }
            sb.append(searchString.substring(0, startIndex)).append("*******");
            searchString = searchString.substring(endIndex);
            matcher = PASSWORD_PATTERN.matcher(searchString);
        }
        return sb.append(searchString).toString();
    }

    public static void main(String[] args) throws IOException {
        System.out.println(JSON.parseObject(null));
    }
}
